#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QPainter>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>

LoginWidget::LoginWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    connect(client,&ClientSocket::loginReply,this,&LoginWidget::loginReply);
    connect(client,&ClientSocket::signupReply,this,&LoginWidget::signupReply);
}

LoginWidget::~LoginWidget()
{
    delete ui;
}

void LoginWidget::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    QPixmap pix(":/image/dog.jpg");
    painter.drawPixmap(0,0,width(),height(),pix,0,0,pix.width(),pix.height());
    QWidget::paintEvent(e);
}

void LoginWidget::loginReply(const QJsonObject &reply)
{
    QString status = reply.value("status").toString();
    if(status == "login_ok"){
        chat_widget = new ChatWidget;
        chat_widget->setCurrentUserName(ui->lineEdit_account->text());
        chat_widget->show();
        this->hide();
    }else if(status == "login_fail"){
        QMessageBox::critical(this,"登陆失败",reply.value("msg").toString());
    }
}

void LoginWidget::signupReply(const QJsonObject &reply)
{
    QString status = reply.value("status").toString();
    if(status == "signup_ok"){
        QMessageBox::information(this,"注册","注册成功!");
    }else if(status == "signup_fail"){
        QMessageBox::critical(this,"注册失败",reply.value("msg").toString());
    }
}

void LoginWidget::on_pushbutton_login_clicked()
{
    if(!client->isConnected()){
        QMessageBox::critical(this,"网络异常","网络连接失败");
        return ;
    }
    QString user_name = ui->lineEdit_account->text();
    QString user_password = ui->lineEdit_password->text();
    client->login(user_name,user_password);
}

void LoginWidget::on_pushbutton_logon_clicked()
{
    if(!client->isConnected()){
        QMessageBox::critical(this,"网络异常","网络连接失败");
        return ;
    }
    QString user_name = ui->lineEdit_account->text();
    QString user_password = ui->lineEdit_password->text();
    client->signup(user_name,user_password);
}
